package com.nineclock.message.service.impl;

import com.nineclock.common.utils.BeanHelper;
import com.nineclock.message.dto.NcMessageDto;
import com.nineclock.message.dto.NcMessageQueryDTO;
import com.nineclock.message.jpush.JPushManager;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.message.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private JPushManager jPushManager;

    @Override
    public void pushMessage(NcMessage ncMessage) throws Exception{
        // 保存通知记录到mongoDB
        ncMessage.setCreateTime(new Date());
        mongoTemplate.insert(ncMessage);

        // 调用极光API，推送通知
        jPushManager.sendNotificationByAlias(ncMessage.getTitle(), ncMessage.getContent(),
                ncMessage.getTargets(), null);
    }

    @Override
    public List<NcMessageDto> findMessageRecord(NcMessageQueryDTO queryDTO) {
        // 创建查询对象
        Query query = new Query();

        if(!StringUtils.isEmpty(queryDTO.getId())){
            query.addCriteria(new Criteria("_id").is(queryDTO.getId()));
        }

        if(queryDTO.getUserId() !=null){ // 申请人用户id
            query.addCriteria(new Criteria("applyUserId").is(queryDTO.getUserId()));
        }

        if(!StringUtils.isEmpty(queryDTO.getType())){
            query.addCriteria(new Criteria("messageType").is(queryDTO.getType()));
        }

        if(queryDTO.getTargetId() !=null){
            query.addCriteria(new Criteria("approveUserId").is(queryDTO.getTargetId()));
        }

        // 指定排序参数，根据审批状态升序排序
        query.with(Sort.by(Sort.Order.asc("approveStatue")));

        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);

        if(!CollectionUtils.isEmpty(messageList)){
            return BeanHelper.copyWithCollection(messageList, NcMessageDto.class);
        }

        return null;
    }

    @Override
    public void updateMessageWithApproved(String msgId) {
        Query query = new Query(new Criteria("_id").is(msgId));

        // 设置更新的值
        Update update = new Update();
        update.set("useStatus", 1); // 已读
        update.set("approveStatue", 1); // 已审批

        mongoTemplate.updateMulti(query, update, NcMessage.class);
    }
}
